<template>
  <div class="avatar-upload">
    <el-upload
      action=""
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
      :on-progress="onProgress"
      :on-success="onSuccess"
    >
      <div class="avatar-upload__item">
        <img class="avatar-upload__img" :src="imageUrl" alt="" />
      </div>

      <div class="avatar-upload__item">
        <el-icon :size="36"><picture-filled /></el-icon>
        <span>选择头像</span>
      </div>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { PictureFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { ref } from 'vue'

defineOptions({ name: 'AvatarUpload' })

const props = defineProps({
  // 限制大小
  limitSize: { type: Number, default: 2 }
})

const imageUrl = ref<string>('')

// 上传前
async function beforeUpload(file: File) {
  console.log('file', file)
  if (file.size / 1024 / 1024 >= props.limitSize) {
    ElMessage.error(`上传文件大小不能超过 ${props.limitSize}MB!`)
    return false
  }
  return true
}

// 覆盖默认的上传请求
function httpRequest(options: any) {
  return request.post(
    '/admin/base/comm/upload',
    { file: options.file },
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: options.onProgress
    }
  )
}

// 文件上传时的钩子
function onProgress(evt: any) {
  console.log('onProgress', evt)
}

// 文件上传成功时的钩子
function onSuccess(response: string) {
  console.log('onSuccess', response)
  imageUrl.value = response
}
</script>

<style scoped>
.avatar-upload {
  .avatar-upload__item {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 120px;
    height: 120px;
    line-height: 32px;
    font-size: 14px;
    color: var(--el-text-color-regular);
    border-radius: 6px;
    background-color: var(--el-fill-color-light);
    cursor: pointer;
    user-select: none;
    overflow: hidden;
  }

  .avatar-upload__img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
</style>
